package com.hs.Lotto;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Formatter;
import java.util.Random;
import java.util.zip.Inflater;

import com.hs.Log.DebugPrint;
import com.hs.SimpleLotteryInfo.R;
import com.hs.http.HttpConn;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class LottoInformationActivity extends Activity
{
	private final static String LOG_TAG = "LottoInformationActivity";
	
	private TextView m_txtTitle;
	private TextView m_txtBody;
	private Context m_cxt;
	
	private LottoParser m_lParser;
	
	private static final int HANDLER_EVT_ON_CONNECT 						= 0x00001;
	private static final int HANDLER_EVT_ON_TOAST							= 0x00002;
	private static final int HANDLER_EVT_ON_PARSE							= 0x00003;
	private static final int HANDLER_EVT_ON_CONNECT_TURN 					= 0x00004;
	private static final int HANDLER_EVT_ON_CREATE_NUMBERS 					= 0x00005;
	private static final int HANDLER_EVT_ON_SHOW_RESULT 					= 0x00006;
	
	
	private final String STR_DUMMY_URL = "http://www.645lotto.net/resultall/dummy.asp";
	private final String STR_TURN_URL = "http://www.645lotto.net/resultall/%d.asp";
	
	private final int SCR_MODE_PROGRESS = 100;
	private final int SCR_MODE_DEFAULT 	= 101;
	private final int SCR_MODE_ERROR	= 102;
	
	private int m_nLastTurn;
	
	
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lottoinformationactivity_layout);
                
        init();
        
        m_handler.sendEmptyMessage(HANDLER_EVT_ON_CONNECT);
    }
	
	public void onResume()
	{
		super.onResume();
	}
	
	public void onPause()
	{
		super.onPause();
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		
	}
	
	public void onConfigurationChanged(Configuration newConfig)
	{
		super.onConfigurationChanged(newConfig);
	}
	
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		menu.clear();
		
		MenuInflater menuInf = getMenuInflater();
		menuInf.inflate(R.menu.menu , menu);
		
		if( getScreenMode() == SCR_MODE_PROGRESS )
		{
			menu.findItem(R.id.menu_id_refresh).setVisible(false);
			menu.findItem(R.id.menu_id_check_my_number).setVisible(false);
			menu.findItem(R.id.menu_id_create_number).setVisible(false);
			menu.findItem(R.id.menu_id_find_lucky_number).setVisible(false);
		} // end if( getScreenMode() == SCR_MODE_PROGRESS )
		
		else if( getScreenMode() == SCR_MODE_DEFAULT )
		{
			// 
		} // end else if( getScreenMode() == SCR_MODE_DEFAULT )
		
		else if( getScreenMode() == SCR_MODE_ERROR )
		{
			menu.findItem(R.id.menu_id_check_my_number).setVisible(false);
			menu.findItem(R.id.menu_id_create_number).setVisible(false);
			menu.findItem(R.id.menu_id_find_lucky_number).setVisible(false);
		} // end else if( getScreenMode() == SCR_MODE_ERROR )
		
		return true;
	}
	
	public boolean onOptionsItemSelected( final MenuItem item )
	{
		if( item.getItemId() == R.id.menu_id_refresh )
		{
			setScreen( SCR_MODE_PROGRESS );
			runMenuRefresh();
		} // end if( item.getItemId() == R.id.menu_id_refresh )
		
		else if( item.getItemId() == R.id.menu_id_find_lucky_number )
		{
			runMenuTurnNumber();
		} // end else if( item.getItemId() == R.id.menu_id_find_lucky_number )
		
		else if( item.getItemId() == R.id.menu_id_create_number )
		{
			runMenuCreateLuckyNmber( null );
		} // end else if( item.getItemId() == R.id.menu_id_create_number )
		
		else if( item.getItemId() == R.id.menu_id_check_my_number )
		{
			runMenuCheckMyNumber();
		} // end else if( item.getItemId() == menu_id_check_my_number )
		
		return true;
	}
	
	private void init()
	{
		m_cxt = this;
		
		m_txtTitle = (TextView)findViewById(R.id.txt_id_title);
		m_txtBody = (TextView)findViewById(R.id.txt_id_body);
	}
	
	private void parseLotto( final String _str )
	{
		if( m_lParser == null )
		{
			m_lParser = new LottoParser();
		} // end if( m_lParser == null )
		else
		{
			m_lParser.clear();
		} // end else
		
		m_lParser.setData(_str);
		
		new Thread(new Runnable()
		{
			public void run()
			{
				m_lParser.parse();
				m_handler.sendEmptyMessage(HANDLER_EVT_ON_PARSE);
			}
		}).start();
	}
	
	private void setData()
	{
		setScreen(SCR_MODE_DEFAULT);
		
		if( m_nLastTurn == 0 )
		{
			m_nLastTurn = Integer.valueOf(m_lParser.getTurn());
		} // end if( m_nLastTurn == 0 )
		
		m_txtTitle.setText(m_lParser.getTurn() + m_cxt.getString(R.string.str_turn));
		
		StringBuilder strb = new StringBuilder();
		strb.append(new Formatter().format(m_cxt.getString(R.string.str_lucky_number_index), 1).toString() + " : " + m_lParser.get1stBall() + "\n" + "\n");
		strb.append(new Formatter().format(m_cxt.getString(R.string.str_lucky_number_index), 2).toString() + " : "  + m_lParser.get2ndBall() + "\n" + "\n");
		strb.append(new Formatter().format(m_cxt.getString(R.string.str_lucky_number_index), 3).toString() + " : "  + m_lParser.get3rdBall() + "\n" + "\n");
		strb.append(new Formatter().format(m_cxt.getString(R.string.str_lucky_number_index), 4).toString() + " : "  + m_lParser.get4thBall() + "\n" + "\n");
		strb.append(new Formatter().format(m_cxt.getString(R.string.str_lucky_number_index), 5).toString() + " : "  + m_lParser.get5thBall() + "\n" + "\n");
		strb.append(new Formatter().format(m_cxt.getString(R.string.str_lucky_number_index), 6).toString() + " : "  + m_lParser.get6thBall() + "\n" + "\n");
		strb.append(m_cxt.getString(R.string.str_bonus_number) + " : "  + m_lParser.getBonusBall());
		
		m_txtBody.setText(strb.toString());
		
	}
	
	private void setScreen( int _nMode )
	{
		LinearLayout linPro = (LinearLayout)findViewById(R.id.lin_id_load);
		LinearLayout linDefault = (LinearLayout)findViewById(R.id.lin_id_default);
		LinearLayout linError = (LinearLayout)findViewById(R.id.lin_id_error);
		
		switch( _nMode )
		{
			case SCR_MODE_PROGRESS:
			{
				linPro.setVisibility(View.VISIBLE);
				linDefault.setVisibility(View.GONE);
				linError.setVisibility(View.GONE);
				break;
			}
			
			case SCR_MODE_DEFAULT:
			{
				linPro.setVisibility(View.GONE);
				linDefault.setVisibility(View.VISIBLE);
				linError.setVisibility(View.GONE);
				break;
			}
			
			case SCR_MODE_ERROR:
			{
				linPro.setVisibility(View.GONE);
				linDefault.setVisibility(View.GONE);
				linError.setVisibility(View.VISIBLE);
				break;
			}
		}
	}
	
	private int getScreenMode()
	{
		LinearLayout linPro = (LinearLayout)findViewById(R.id.lin_id_load);
		LinearLayout linDefault = (LinearLayout)findViewById(R.id.lin_id_default);
		LinearLayout linError = (LinearLayout)findViewById(R.id.lin_id_error);
		
		if( linPro.getVisibility() == View.VISIBLE )
		{
			return SCR_MODE_PROGRESS;
		} // end if( linPro.getVisibility() == View.VISIBLE )
		
		else if( linDefault.getVisibility() == View.VISIBLE )
		{
			return SCR_MODE_DEFAULT;
		} // end else if( linDefault.getVisibility() == View.VISIBLE )
		
		else if( linError.getVisibility() == View.VISIBLE )
		{
			return SCR_MODE_ERROR;
		} // end else if( linError.getVisibility() == View.VISIBLE )
		
		return SCR_MODE_DEFAULT;
		
	}
	
	private void runMenuRefresh()
	{
		m_handler.sendEmptyMessage(HANDLER_EVT_ON_CONNECT);
	}
	
	private void runMenuTurnNumber()
	{
		final LinearLayout linDialog = (LinearLayout)View.inflate(this, R.layout.lottoinformation_dialog_turn_lucky_number , null);
		
		final EditText edt = (EditText)linDialog.findViewById(R.id.edt_id_turn);
		edt.setHint( new Formatter().format( getString(R.string.str_input_turn_hint) , m_nLastTurn).toString() );
		new AlertDialog.Builder(this).setTitle(getString(R.string.str_title_turn)).setView(linDialog).setPositiveButton(getString(R.string.str_dialog_btn_ok), new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface _dialog, int _whichBtn)
			{
				if( edt.getText().length() > 0 )
				{
					int nVal = Integer.valueOf(edt.getText().toString());
					if( nVal > m_nLastTurn )
					{
						m_handler.sendMessage(m_handler.obtainMessage(HANDLER_EVT_ON_TOAST, m_cxt.getString(R.string.str_dialog_error_no_range)));
					} // end if( nVal > m_nLastTurn )
					
					else
					{
						m_handler.sendMessage( m_handler.obtainMessage(HANDLER_EVT_ON_CONNECT_TURN , nVal) );
					} // end else
					
					
				} // end if( edt.getText().length() > 0 )
			}
		}).show();
	}
	
	private void runMenuCheckMyNumber()
	{
		Intent i = new Intent( this , CheckMyNumbersActivity.class );
		i.putExtra(CheckMyNumbersActivity.INTENT_KEY_LAST_TURN, m_nLastTurn);
		startActivity(i);
	}
	
	private void runMenuCreateLuckyNmber( final ArrayList<Integer> _arrLst )
	{
		if( _arrLst == null )
		{
			final Random r = new Random();
			
			new Thread( new Runnable()
			{
				public void run()
				{
					ArrayList<Integer> arrLst = new ArrayList<Integer>();
					
					while(arrLst.size() < 6)
					{
						int nVal = r.nextInt(44) + 1;
						
						if( arrLst.contains(nVal) == false )
						{
							arrLst.add(nVal);
						} // end if( arrLst.contains(nVal) == false )
						
					} // end while(arrLst.size() < 6)
					
					m_handler.sendMessage( m_handler.obtainMessage(HANDLER_EVT_ON_CREATE_NUMBERS , arrLst) );
				}
				
			}).start();
			
		} // end if( _bCreateNum == true )
		
		else
		{
			final LinearLayout linDialog = (LinearLayout)View.inflate(this, R.layout.lottoinformation_dialog_create_lucky_number , null);
			
			final TextView txt = (TextView)linDialog.findViewById(R.id.txt_id_create_number);
			
			txt.post(new Runnable()
			{
				
				public void run()
				{
					StringBuilder strB = new StringBuilder();
					strB.append(m_cxt.getString(R.string.str_dialog_created_number_is));
					int nSize = _arrLst.size();
					
					Collections.sort(_arrLst);
					
					for( int i = 0 ; i < nSize ; i++ )
					{
						strB.append(_arrLst.get(i));
						
						if( i != nSize -1 )
							strB.append(",");
					} // end for( int i = 0 ; i < nSize ; i++ )
					
					strB.append(m_cxt.getString(R.string.str_dialog_created_number_done));
					
					txt.setText(strB.toString());
				}
			});
			
			new AlertDialog.Builder(this).setTitle(getString(R.string.str_title_create_lucky_number)).setView(linDialog).setPositiveButton(getString(R.string.str_dialog_btn_retry), new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface _dialog, int _whichBtn)
				{
					runMenuCreateLuckyNmber(null);
				}
			}).show();
			
		} // end else
	}

	private void showResult( ArrayList<String> _arrLst )
	{
		final LinearLayout linDialog = (LinearLayout)View.inflate(this, R.layout.lottoinformation_dialog_show_result , null);
		final TextView txt = (TextView)linDialog.findViewById(R.id.txt_id_result);
		
		
		
		new AlertDialog.Builder(this).setTitle(getString(R.string.str_dialog_result)).setView(linDialog).setPositiveButton(getString(R.string.str_dialog_btn_ok), null).show();
	}
	
	
	private Handler m_handler =  new Handler()
	{
		public void handleMessage(Message _msg)
		{
			int nWhat = _msg.what;
    		
    		switch( nWhat )
    		{
    			case HANDLER_EVT_ON_CONNECT:
    			{
    				HttpConn hc = new HttpConn(m_cxt, m_handler);
    				hc.getData(STR_DUMMY_URL);
    				break;
    			}
    			
    			case HANDLER_EVT_ON_CONNECT_TURN:
    			{
    				Integer iVal = (Integer)_msg.obj;
    				setScreen(SCR_MODE_PROGRESS);
    				HttpConn hc = new HttpConn(m_cxt, m_handler);
    				hc.getData(new Formatter().format(STR_TURN_URL, iVal.intValue()).toString());
    				break;
    			}
    			
    			case HANDLER_EVT_ON_TOAST:
    			{
    				String str = (String)_msg.obj;
	    			Toast.makeText(m_cxt, str , Toast.LENGTH_SHORT).show();
    				break;
    			}
    			
    			case HttpConn.HTTP_EVT_OK:
    			{
    				String str = (String)_msg.obj;
    				parseLotto(str);
    				break;
    			}
    			
    			case HttpConn.HTTP_EVT_FAIL:
    			{
    				setScreen(SCR_MODE_ERROR);
    				String str = (String)_msg.obj;
	    			Toast.makeText(m_cxt, str , Toast.LENGTH_SHORT).show();
    				break;
    			}
    			
    			case HttpConn.HTTP_EVT_EXCEPTION:
    			{
    				setScreen(SCR_MODE_ERROR);
    				String str = (String)_msg.obj;
	    			Toast.makeText(m_cxt, str , Toast.LENGTH_SHORT).show();
    				break;
    			}
    			
    			case HANDLER_EVT_ON_PARSE:
    			{
    				setData();
    				break;
    			}
    			
    			case HANDLER_EVT_ON_CREATE_NUMBERS:
    			{
    				runMenuCreateLuckyNmber( (ArrayList<Integer>)_msg.obj );
    				break;
    			}
    			
    			case HANDLER_EVT_ON_SHOW_RESULT:
    			{
    				ArrayList<String> arrLst = (ArrayList<String>)_msg.obj;
    				
    				showResult(arrLst);
    				
    				break;
    			}
    		} // end switch( nWhat )
		}
	};
}
